<template>
  <div class="display">
    <el-card class="box-card cardNoPadding" >
      <template #header>
        <div class="customerTitle1">
          <div>
            <span class="leve_title" >{{route.query.uid ? salesStatus == '1'?'售后单变更' : '售后单处理' : '售后单新建'}}</span>
          </div>
          <div>
            <el-button
              @click="back"
            >
              返回
            </el-button>
            <el-button
              :loading="buttonLoading"
              v-if = "!state || state == '草稿'"
              class="customerButton1"
              plain
              type="primary"
              @click="submit(2)"
            >
              暂存
            </el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submit(1)">
              提交
            </el-button>
          </div>
        </div>
      </template>
<!--      <div>-->
<!--        <SalesStage :steps="arr_approve" @clickValue="(va:any)=>{-->
<!--          console.log(va)-->
<!--        }"/>-->
<!--      </div>-->
    </el-card>
   <div>
     <OrderingInformation  ref="orderRef" :status="state"/>
   </div>
  <div>
    <DetailInformation ref="detailRef"/>
  </div>
    <el-card class="box-card">
      <template #header>
        <div class="customerTitle1">
          <span class="leve2_title" >添加图片</span>
        </div>
      </template>
      <div>
<!--        @delete="handleDelete"  删除-->
        <vab-upload
          drag
          size="8"
          ref="uploadPictureRef"
          :fileList="fileList"
        />
<!--        <Picture :file-list="fileList"/>-->
      </div>
    </el-card>
    <el-dialog v-model="productQuantityOpen" width="60%" center>
      <template #header>
      <span>
        <el-icon style="font-size: 66px;color: #f7ae57"><WarningFilled /></el-icon>
        <div class="titleProduct">
          产品库存不足
        </div>
      </span>
      </template>
      <span>
    <div v-for="(item, index) in productQuantityList" :key="index">
      <p>
        {{item.goods_name}}产品销售数量{{Number(item.sales_num).toFixed(0)}},当前库存
      <span style="color: #f59a23">
        {{Number(item.quantity).toFixed(0)}}
      </span>
      ,库存不足,
      </p>
    </div>
      <div>
        请更新销售数量或者调拨后在进行订单提交
      </div>
    </span>
      <template #footer>
      <span class="dialog-footer">
          <el-button type="primary" @click="productQuantityOpen = false">
          知道了
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import OrderingInformation from './OrderingInformation.vue'
import DetailInformation from './DetailInformation.vue'
import {productDeleteImg} from "/@/api/dms/product";
import {ElMessage} from "element-plus";
import SalesStage from './SalesStage.vue'
import router from "/@/router";
import {getRefundChange, getRefundCreate, getRefundInfo} from "/@/api/dms/refund";
import salesOrderStore from "/@/views/afterSales/storeList";
defineOptions({
    name: 'AddSales',
  })
// 产品不足的弹窗
const productQuantityOpen = ref(false)
const productQuantityList = ref<any>([])
const buttonLoading = ref<any>(false)
const arr_approve = ref([
  { title: '售后单', active: true,type:1},
  { title: '快递运输', active: false,type:2 },
  { title: '退货入库单', active: false,type:3 },
  { title: '退货确认', active: false,type:4 },
])
const route:any = useRoute()
const salesOrderStoreList:any = salesOrderStore()
let fileList = ref<any>([])
const uploadPictureRef =  ref<any>(undefined)
const orderRef =  ref<any>(undefined)
const detailRef =  ref<any>(undefined)
const state  = ref<any>(undefined)
const salesStatus:any = ref(localStorage.getItem('salesStatus'))
  //删除图片时间
const handleDelete = (row: any) => {
  productDeleteImg({ id: row.id }).then(res => {
    ElMessage({
      message: '删除成功',
    })
  })
}
// 返回
const back = ()=>{
  salesOrderStoreList.set_orderList(undefined)
  router.push('/sales/salesOrder')
  localStorage.removeItem('salesStatus')
}
// 表单验证
const check = ()=> {
  const orderList = detailRef.value.salesOrderList.filter((item:any)=> item.type !== '无')
  const product_list = orderList
  const check1 = product_list.map((item: any, index: any) => {
    if (item.return_number == '' || item.return_number == undefined) {
      ElMessage.warning(`序号为 ${index + 1}退货数量不能为0`)
      return false
    } else {
      return true
    }
  })
  const check6 = [...check1,].every(i=>i==true)
  return check6
}
// 提交
const submit = async (type:any)=>{
  buttonLoading.value= true
  const imageList = uploadPictureRef.value!.list.map((item:any,index:any)=>{return {index:index+1,url:item.response ? item.response : item.url}})
  const orderList = detailRef.value.salesOrderList
  const formList = {
    reason:orderRef.value.form_new_list.reason || '',    //售后理由
    remark:orderRef.value.form_new_list.remark || '',   //售后备注
    express_sn:orderRef.value.form_new_list.express_sn || '',     //快递单号
    express_company:orderRef.value.form_new_list.express_company || '',    //快递公司
    type:orderRef.value.form_new_list.type|| '',
    scene: type == 1 ?'save' : 'draft',//提交场景   草稿：draft 提交审核save
    orderItem:orderList,//产品信息
    attachment:imageList,// 图片
  }
  const checkList = check()
  await orderRef.value.form_new_date.validate((valid: any, fields: any) => {
    if(valid && checkList){
      if(route.query.uid){
        getRefundChange({...formList,afterSalesUid:orderRef.value.form_new_list.uid}).then((data:any)=>{
          if(data.code == 200){
            if(data.data.result == false){
              productQuantityList.value = data.data.error_info || []
              productQuantityOpen.value = true
            }else {
              salesOrderStoreList.set_orderList(undefined)
              salesOrderStoreList.set_salesSortValue({label:'return',type:1})
              router.push('/sales/salesOrder')
              if(type == 1){
                ElMessage.success(`提交成功`)
              }else if(type == 2){
                ElMessage.success(`暂存成功`)
              }
            }
          }
          buttonLoading.value = false
        })
      }else {
        getRefundCreate({...formList}).then((data:any)=>{
          if(data.code == 200){
            if(data.data.result == false){
              productQuantityList.value = data.data.error_info || []
              productQuantityOpen.value = true
            }else {
              salesOrderStoreList.set_orderList(undefined)
              salesOrderStoreList.set_salesSortValue({label:'return',type:1})
              router.push('/sales/salesOrder')
              if(type == 1){
                ElMessage.success(`提交成功`)
              }else if(type == 2){
                ElMessage.success(`暂存成功`)
              }
            }
          }
          buttonLoading.value = false
        })
      }

    }
  })
}
const loading = ref<boolean>(false)
//详情接口
const getOrderInfo = ()=>{
  if(route.query.uid){
    getRefundInfo({afterSalesUid:route.query.uid}).then((data:any)=>{
      if(data.code == 200){
        // detailRef.value.salesOrderList = data.data?.after_item
        // detailRef.value.salesOrderDetailList = data.data.goods_item
       /* orderRef.value.form_new_list = {reason:data.data.info.reason,    //售后理由
          remark:data.data.info.remark,   //售后备注
          express_sn:data.data.info.express_sn || '',     //快递单号
          express_company:data.data.info.express_company || '',    //快递公司
          type:data.data.info.type,
          uid:data.data.info.uid,
          created_at:data.data.info.created_at,
        }*/
        orderRef.value.form_new_list ={...data.data.info}
        //JSON.parse(data.data.info.attachment)
          fileList.value = data.data.info.attachment !== null ? [...data.data.info.attachment] : []
        state.value = data.data.info.status_text
        salesOrderStoreList.set_salesSortValue({label:data.data.info.type,type:1})
        salesOrderStoreList.set_orderList(data.data)
      }
    })
  }
}
/*// 离开当前页面清空数据
onBeforeRouteLeave((to, from, next)=>{
  salesOrderStoreList.set_orderList(undefined)
  salesOrderStoreList.set_salesSortValue({label:'',type:1})
  localStorage.removeItem('salesStatus')
  next()
})*/
onMounted(()=>{
  getOrderInfo()
})
</script>

<style lang="scss" scoped>
@import "../index";
.cardNoPadding{
  :deep(){
    .el-card__body{
      padding: 0px;
    }
  }
}
</style>

